import { ref, readonly } from 'vue';
import hexToRgb from '../util/hexToRgb.js';

const SYSTEM_CONFIG = 'systemConfig';

export default function useSystemSubject() {
  const systemColorRef = ref();

  const systemColorReadonly = readonly(systemColorRef);

  const setSystemColor = (color) => {
    systemColorRef.value.color = color;
    setStore(systemColorRef.value);
  };

  const getStore = () => {
    return localStorage.getItem(SYSTEM_CONFIG)
      ? JSON.parse(localStorage.getItem(SYSTEM_CONFIG))
      : null;
  };
  const setStore = (data) => {
    localStorage.setItem(SYSTEM_CONFIG, JSON.stringify(data));
  };
  // 应用主题
  const initSystemColorRef = () => {
    systemColorRef.value = getStore() || { color: '#5768e7' };
  };
  initSystemColorRef();

  // 页面设置css变量
  const initSystem = (cls) => {
    // 设置主题色
    const appDom = document.querySelector(cls);
    const [r, g, b] = hexToRgb(systemColorReadonly.value.color);
    appDom.style.setProperty(
      '--system-primary-color',
      systemColorReadonly.value.color
    );
    appDom.style.setProperty(
      '--system-active-bg-color',
      `rgba(${r},${g},${b},0.08)`
    );
  };
  return {
    systemColorReadonly,
    setSystemColor,
    initSystem,
  };
}
